package com.xmler.plugin.adbrocket.adb

import com.google.common.util.concurrent.ThreadFactoryBuilder
import com.intellij.openapi.project.Project
import com.xmler.plugin.adbrocket.ObjectGraph
import com.xmler.plugin.adbrocket.adb.command.*
import com.xmler.plugin.adbrocket.utils.AdbUtil
import com.xmler.plugin.adbrocket.utils.Logger
import java.util.concurrent.Executors

object AdbFacade {
    private val EXECUTOR =  Executors.newCachedThreadPool(ThreadFactoryBuilder().setNameFormat("AdbRocket-%d").build())

    fun fetchDevices(project: Project): DeviceResultList? =
        project.getComponent(ObjectGraph::class.java)
            .deviceFeetcher
            .fetch()

    fun appUninstall(project: Project, result: DeviceResult?) = execute(project, result, UninstallCmd())
    fun appKill(project: Project, result: DeviceResult?) = execute(project, result, KillCmd())
    fun appStart(project: Project, result: DeviceResult?) = execute(project, result, StartDefaultActivityCmd())
    fun appRestart(project: Project, result: DeviceResult?) = execute(project, result, RestartDefaultActivityCmd())
    fun clearData(project: Project, result: DeviceResult?) = execute(project, result, ClearDataCmd())
    fun clearDataAndRestartActivity(project: Project, result: DeviceResult?) = execute(project, result, ClearDataAndRestartCmd())

    fun usbToWifiConnect(project: Project, result: DeviceResult?) = execute(project, result, UsbToWifiConnectCmd())

    fun keyboradInput(project: Project, result: DeviceResult?, text: String) = execute(project, result, KeyboardInputCmd(text))
    //
    fun executeShell(project: Project, result: DeviceResult?, runnable: ICommand) {
        execute(project, result, runnable)
    }
    private fun execute(project: Project, result: DeviceResult?, runnable: ICommand) {
        if (AdbUtil.isGradleSyncInProgress(project)) {
            //
            return
        }

        if (result != null) {
            EXECUTOR.submit { runnable.run(project, result.device, result.facet, result.packageName, result.display) }
        } else {
            // TODO No device found
            Logger.e("No device found")
        }
    }
}